package guoanmaker.operator.business.service;

import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import guoanmaker.operator.business.model.OperatorCode;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.repository.OperatorCodeRepository;
import guoanmaker.operator.helper.common.abstractobj.ApiController;
import guoanmaker.operator.helper.common.util.SMSHelper;
import guoanmaker.operator.helper.common.util.StdRandom;


@Service
public class OperatorSendCodeService {
	
	
	
	@Autowired
	private  OperatorCodeRepository  operatorCodeRepository;
	
	
	
	
	
	/**
	 * 
	* @Description: 发送验证码并且将验证码及用户手机号入库 使用@Transactional处理事务
	* @param telephone 用户手机号
	* @param @throws Exception
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
    public ReturnResult sendCode(String name,String telephone) throws Exception{
    	ReturnResult returnResult = new ReturnResult();
    	String url = ApiController.SMS_URL;
		String username = ApiController.SMS_USERNAME;
		String password = ApiController.SMS_PASSWORD;
		String epid = ApiController.SMS_EPID;
		String param = "";
		String code="";
	    String sendingcode = "";
		code=getSixCode();
		OperatorCode  operatorCode=new OperatorCode();
		if(telephone!=null&&name!=null){
			//保存5分钟后的时间，验证时用now即可
	        long curren = System.currentTimeMillis();
	        curren += 5 * 60 * 1000;
	        Date da = new Date(curren);
	        operatorCode =operatorCodeRepository.selectByObject(code,telephone,new Date());
	      
			if(null!=operatorCode&&null!=operatorCode.getCodetext()){
				sendingcode = operatorCode.getCodetext();
				operatorCode.setDate(da);
				operatorCodeRepository.save(operatorCode);
			} else {
				 operatorCode=new OperatorCode();
			}
		if("".equals(sendingcode)){
			        operatorCode.setDate(da);
			        operatorCode.setPhone(telephone);
			        operatorCode.setCodetext(code);
			        operatorCodeRepository.save(operatorCode);
			        sendingcode=code;
			}
		}
		param = "username=" + username + "&password=" + password + "&phone=" + telephone + "&epid=" + epid
				+ "&linkid=&subcode=" + "&message=" + URLEncoder.encode("尊敬的"+name+"先生/女士，您好，"
						+ "您正在找回登录密码，验证码："+sendingcode+"，如非本人操作，请忽略本短信 <国安创客>。", "gb2312");
		String result = SMSHelper.SendGET(url, param);
		if(result.equals("00")){
    		returnResult.setKey("success");
    		returnResult.setValue(sendingcode);
		}else if(result.equals("2")){
				returnResult.setKey("error");
	    		returnResult.setValue("鉴权失败");
		}else{
				returnResult.setKey("error");
	    		returnResult.setValue("发送失败");
		}
		return returnResult;
    }
	@Transactional
	public ReturnResult sendCodeforAddAccount(String name,String pwd,String telephone,String account) throws Exception{
		ReturnResult returnResult = new ReturnResult();
		String url = ApiController.SMS_URL;
		String username = ApiController.SMS_USERNAME;
		String password = ApiController.SMS_PASSWORD;
		String epid = ApiController.SMS_EPID;
		String param = "";
		String code="";
		code=pwd;
		param = "username=" + username + "&password=" + password + "&phone=" + telephone + "&epid=" + epid
				+ "&linkid=&subcode=" + "&message=" + URLEncoder.encode("尊敬的"+name+"您好，公司为您创建了运营管理后台账号，"
						+ "账号："+account+",密码为："+code+",请您及时登录进行密码修改。", "gb2312");
		String result = SMSHelper.SendGET(url, param);
		if(result.equals("00")){
			returnResult.setKey("success");
			returnResult.setValue(code);
		}else if(result.equals("2")){
			returnResult.setKey("error");
			returnResult.setValue("鉴权失败");
		}else{
			returnResult.setKey("error");
			returnResult.setValue("发送失败");
		}
		return returnResult;
	}
	
	// 获取6位数字验证码
	public static String getSixCode(){
		StringBuilder code = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			code.append(String.valueOf(random.nextInt(10)));
		}
		
		String smsText = "" + code;
		return  smsText;
	}
	
	// 获取6位随机数加字母
			public static String getSixCodeforAccount(){
				  //数组，用于存放随机字符
		        char[] chArr = new char[6];
		        //为了保证必须包含数字、大小写字母
		        chArr[0] = (char)('0' + StdRandom.uniform(0,10));
		        chArr[1] = (char)('A' + StdRandom.uniform(0,26));
		        chArr[2] = (char)('a' + StdRandom.uniform(0,26));
		        char[] codes = { '0','1','2','3','4','5','6','7','8','9',
		                         'A','B','C','D','E','F','G','H','I','J',
		                         'K','L','M','N','O','P','Q','R','S','T',
		                         'U','V','W','X','Y','Z','a','b','c','d',
		                         'e','f','g','h','i','j','k','l','m','n',
		                         'o','p','q','r','s','t','u','v','w','x',
		                         'y','z'};
		        //charArr[3..len-1]随机生成codes中的字符
		        for(int i = 3; i < 6; i++){
		            chArr[i] = codes[StdRandom.uniform(0,codes.length)];
		        }
		        
		        //将数组chArr随机排序
		        for(int i = 0; i < 6; i++){
		            int r = i + StdRandom.uniform(6 - i);
		            char temp = chArr[i];
		            chArr[i] = chArr[r];
		            chArr[r] = temp;
		        }
		        
		        StringBuffer sb = new StringBuffer();
		        for(int i = 0; i < chArr.length; i++)
		        { 
		        sb. append(chArr[i]);
		        }
		        String s = sb.toString();
		        
		        return s;
			}
			
			
			@Transactional
			public ReturnResult sendMessage(String telephone,String mesContent) throws Exception{
				ReturnResult returnResult = new ReturnResult();
				String url = ApiController.SMS_URL;
				String username = ApiController.SMS_USERNAME;
				String password = ApiController.SMS_PASSWORD;
				String epid = ApiController.SMS_EPID;
				String param = "";
				String code="00";
				param = "username=" + username + "&password=" + password + "&phone=" + telephone + "&epid=" + epid
						+ "&linkid=&subcode=" + "&message=" + URLEncoder.encode(mesContent, "gb2312");
				String result = SMSHelper.SendGET(url, param);
				if(result.equals("00")){
					returnResult.setKey("success");
					returnResult.setValue(code);
				}else if(result.equals("2")){
					returnResult.setKey("error");
					returnResult.setValue("鉴权失败");
				}else{
					returnResult.setKey("error");
					returnResult.setValue("发送失败");
				}
				return returnResult;
			}
			
	
	

}
